import { defineStore } from 'pinia'
import { getAlarmList,addNewAlarm,addTimeGroup,getAllGroupAlarm,deleteTime,deleteGroupAlarm } from '@/api/timeHttp'

// 所有药品
export const useTimeStore = defineStore('time', {
  state: () => ({
    alarmList:[],
    alarmGroupList:[],
  }),
  
  getters: {
    
  },
  
  actions: {

    async getAlarmList() {
        const {data:{data}} = await getAlarmList()
        this.alarmList = data
        console.log(data);
    },
    async addNewAlarm(alarmTime,interval) {
        const time = '2024-10-07 ' + alarmTime + ':00'
        const Interval = interval * 3600
        await addNewAlarm(time,Interval)
        setTimeout(()=>{
          this.getAlarmList()
        },500)
    },
    async addTimeGroup(id,categoryId) {
       await addTimeGroup(id,categoryId)
    },
    async getAllGroupAlarm(){
        const {data:{data}} = await getAllGroupAlarm()
        console.log(data);
        this.alarmGroupList = data
        this.alarmGroupList.sort((a, b) => {
            const timeA = a.alarmTime.split(' ')[1].split(':');
            const timeB = b.alarmTime.split(' ')[1].split(':');
            const hourA = parseInt(timeA[0]);
            const minuteA = parseInt(timeA[1]);
            const hourB = parseInt(timeB[0]);
            const minuteB = parseInt(timeB[1]);
        
            if (hourA < hourB) {
                return -1;
            } else if (hourA > hourB) {
                return 1;
            } else {
                if (minuteA < minuteB) {
                    return -1;
                } else if (minuteA > minuteB) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });
    },
    async deleteTime(id){
        await deleteTime(id)
        this.alarmList = this.alarmList.filter(alarm => alarm.id!== id);
    },
    async deleteGroupAlarm(alarmId,categoryId){
        await deleteGroupAlarm(alarmId,categoryId)
        this.alarmGroupList = this.alarmGroupList.filter(item => {
                return !(item.alarmId === alarmId && item.categoryId === categoryId);
        });
    }
}
}) 